# -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 00:03:28 2020

@author: Wang Tianyu
"""

import pandas as pd
import datetime
from aip import AipNlp
import codecs


APP_ID = '20366338'
API_KEY = 'edwCzK59s10iVkfW6WtajAP4'
SECRET_KEY = 'n0sTr3doqBGnzx1j6DrGcgIpmmwIy8Ey'
client = AipNlp(APP_ID, API_KEY, SECRET_KEY)



def get_sentiments(text):
    try:
        count=1
        sitem=client.sentimentClassify(text)#情感分析
        while (not sitem.get('items',{})) and (count<10):
            count+=1
            sitem = client.sentimentClassify(text)
        sitems=sitem['items'][0]
        #print(sitems)
        #print(type(sitems))
        positive=sitems['positive_prob']#积极概率
        confidence=sitems['confidence']#置信度
        sentiment=sitems['sentiment']#0表示消极，1表示中性，2表示积极
        # tagitems = client.commentTag(text, {'type': 9})  # 评论观点
        # propertys=tagitems['prop']#属性
        # adj=tagitems['adj']#描述词
        group=cur_GROUP
        location=cur_LOCATION
        output='{}\t{}\t{}\t{}\t{}\t{}\n'.format(group,location,text,positive,confidence,sentiment)
        f=codecs.open('seti_beijing-2-1.xls','a+','gb18030')
        f.write(output)
        f.close()
        print('Done')
    except Exception as e:
        print(repr(e))

def get_content():
    data=pd.DataFrame(pd.read_csv('beijing-2-1.csv'))
    data.columns=['GROUP','LOCATION','Text']#重设表头
    #newvdata=row[3]
    return data

data=get_content()
#print(viewdata.head(5))
#print(viewdata.shape[0])
#print(viewdata.shape[1])
# Text=viewdata.Text[0]
# print(Text)
# get_sentiments(Text)

for i in range(data.shape[0]):
    print('正在处理第{}条,还剩{}条'.format(i,data.shape[0]-i))
    cur_GROUP=data.GROUP[i]
    cur_LOCATION=data.LOCATION[i]
    cur_Text=data.Text[i]
    #print(dates)
    #print(type(dates))
    get_sentiments(cur_Text)

